﻿using LPY.LeHealth.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LPY.LeHealth.DAL
{
    using ServiceStack.OrmLite;

    public class CartDal:GenericBaseDAL<Cart>
    {
        /// <summary>
        /// 根据用户Id查询购物车
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<Cart> SelectByUserId(int id)
        {
            using (var cnn=DbConnection)
            {
               var sql= cnn.From<Cart>()
                    .Where(m => m.UserId == id);
               var result= cnn.LoadSelect(sql);

                var hosIds=from s in result
                           select s.Combo.HospitalId;

                var hosSql= cnn.From<HospitalDTO>()
                    .Where(m=>Sql.In(m.Id,hosIds));
                var hos= cnn.Select(hosSql);

                var combos=(from s in result
                           select s.Combo).ToList();
                combos.Merge(hos);

                result.Merge(combos);
               return result;
            }
        }

        /// <summary>
        /// 更新数量
        /// </summary>
        /// <param name="id"></param>
        /// <param name="addCount"></param>
        /// <returns></returns>
        public bool UpdateCount(int id,int addCount,out int count)
        {
            using (var cnn=DbConnection)
            {
               var cart= cnn.SingleById<Cart>(id);
               cart.Count += addCount;
               count = cart.Count;
               var result= cnn.Update(cart);
               return result > 0;
            }
        }

        /// <summary>
        /// 清空用户购物车
        /// </summary>
        /// <param name="uid">用户Id</param>
        /// <returns></returns>
        public bool Clear(int uid)
        {
            using (var cnn=DbConnection)
            {
                var sql = cnn.From<Cart>()
                    .Where(m => m.UserId == uid);
                var result= cnn.Delete(sql);
                return result > 0;
            }
        }
    }
}
